//
//  DB.m
//  Kaoshiti
//
//  Created by lanou3g on 15/10/22.
//  Copyright (c) 2015年 张蒙恩. All rights reserved.
//

#import "DB.h"
#import "OneDetailModel.h"
#import <sqlite3.h>
@implementation DB

static DB *manager = nil;
+ (instancetype)manager
{
    @synchronized(self){
    if (manager == nil) {
        manager = [[DB alloc]init];
    }}
    return manager;
}
static sqlite3 * Db = nil;
- (void)openDB
{
    NSString *sqlPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingString:@"tp.sqlite"];
    int result = sqlite3_open(sqlPath.UTF8String, &Db);
    NSLog(@"%@",sqlPath);
    if (result == SQLITE_OK) {
        NSLog(@"打开Db成功");
    }else{
        NSLog(@"打开Db失败");
    }
    
}
- (void)closeDB
{
    int result = sqlite3_close(Db);
    if (result == SQLITE_OK) {
        NSLog(@"关闭Db成功");
    }else{
        NSLog(@"关闭Db失败");
    }
}
- (void)createTable
{
    NSString *sql = @"CREATE TABLE IF NOT EXISTS type(id INTEGER PRIMARY KEY AUTOINCREMENT, oneData BLOB)";

    int result = sqlite3_exec(Db, sql.UTF8String, NULL, NULL, NULL);

    if (result == SQLITE_OK) {
        NSLog(@"创建表成功");
    }else{
        NSLog(@"创建表失败");
    }
}
- (void)insertModel:(OneDetailModel *)model
{
    NSString *sql = @"INSERT INTO type (oneData) VALUES(?)";
    sqlite3_stmt *stmt = nil;
    int pre = sqlite3_prepare(Db, sql.UTF8String, -1, &stmt, NULL);
    if (pre == SQLITE_OK) {
        NSLog(@"插入豫执行成功");
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
        int bindResult = sqlite3_bind_blob(stmt, 1, data.bytes, (int)data.length, NULL);
        if (bindResult == SQLITE_OK) {
            NSLog(@"绑定成功");
            int resultstep = sqlite3_step(stmt);
            if (resultstep == SQLITE_DONE) {
                NSLog(@"插入数据成功");
            }else{
                NSLog(@"插入数据失败");
            }
        }else{
            NSLog(@"绑定失败");
        }
    }else{
        NSLog(@"插入豫执行失败");
    }
    sqlite3_finalize(stmt);
}
- (void)deleteAllModel
{
    NSString *sql = @"DELETE FROM type";
    int result = sqlite3_exec(Db, sql.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败");
    }
}
- (NSArray *)selectAllModel
{
    NSString *sql = @"SELECT oneData FROM type";
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    sqlite3_stmt *stmt = nil;
    int pre = sqlite3_prepare(Db, sql.UTF8String, -1, &stmt, NULL);
    if (pre == SQLITE_OK) {
        NSLog(@"查询准备成功");
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            NSData *data = [[NSData alloc]initWithBytes:sqlite3_column_blob(stmt, 0) length:sqlite3_column_bytes(stmt, 0)];
            OneDetailModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            [arr addObject:model];
        }
    }else{
        NSLog(@"查询与准备失败");
    }
    sqlite3_finalize(stmt);
    return arr;
}
@end
